<?php
namespace app\admin\controller;
use app\AdminBaseController;
use think\facade\Db;
use app\admin\model\GenerationModel;

class Generation extends AdminBaseController {
    public function index() {
        $result = GenerationModel::order('sort')->select();
        return array(
            'success'=>true,
            'list'=>$result
        );
    }

    public function add() {
        $params = array(
            'name'=>$_POST['name'],
            'sort'=>number_format($_POST['sort']),
            'memo'=>$_POST['memo']
        );

        $isRepeat = GenerationModel::where('sort',$_POST['sort'])->find(1);
        $res;
        if(isset($isRepeat)) {
            $res = array('success'=>false,'message'=>'已经存在'.$_POST['sort'].'世的“'.$isRepeat['name'].'”字辈！');
        } else {
            $result = GenerationModel::insert($params);
            if($result) {
                $res = array('success' => true );
            } else {
                $res = array('success' => false,'message'=>'添加失败！' );
            }
        }
        return $res;
    }

    public function update() {
        $params = array(
            'name'=>$_POST['name'],
            'sort'=>number_format($_POST['sort']),
            'memo'=>$_POST['memo']
        );
        $isRepeat = GenerationModel::where('sort',$_POST['sort'])->where('id','<>',$_POST['id'])->find();
        $res;
        if(isset($isRepeat)) {
            $res = array('success'=>false,'message'=>'已经存在'.$_POST['sort'].'世的“'.$isRepeat['name'].'”字辈！');
        } else {
            $result = GenerationModel::where('id',$_POST['id'])->update($params);
            if($result) {
                $res = array('success' => true );
            } else {
                $res = array('success' => false,'message'=>'修改失败！'  );
            }
        }
        return $res;
    }

    public function del() {
        $count = GenerationModel::where('gid',$_GET['id'])->count();
        $result;
        if($count==0) {
            GenerationModel::where('id',$_GET['id'])->delete();
            $result = array(
                'success'=>true,
                'message'=>'删除成功'
            );
        } else {
            $result = array(
                'success'=>false,
                'message'=>'请先删除相关辈分的成员'
            );
        }
        return $result;
    }
}